package com.randb.easyhttp.https;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

/**
 * User: RandBII
 * Date: 2020/5/12
 * Description:
 */
public class HttpsUtils {

    public static class SSLParams {
        public SSLSocketFactory sSLSocketFactory;
        public X509TrustManager trustManager;
    }

    public static SSLParams getSSLSocketFactory(InputStream bkfFile, String password,
                                                InputStream[] certificates) {
        SSLParams params = new SSLParams();
        try {
            KeyManager[] keyManagers = prepareKeyManager(bkfFile, password);
            TrustManager[] trustManagers = prepareTrustManager(certificates);
            SSLContext sslContext = SSLContext.getInstance("TLS");
            X509TrustManager trustManager1 ;
            if (trustManagers!=null){
                trustManager1 = new MyTrustManager(chooseTrustManager(trustManagers));
            }else{
                trustManager1 = new UnsafeTrustManager();
            }
            sslContext.init(keyManagers,new TrustManager[]{trustManager1},null);
            params.sSLSocketFactory = sslContext.getSocketFactory();
            params.trustManager = trustManager1;
            return params;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private static TrustManager[] prepareTrustManager(InputStream[] certificates) {
        if (certificates == null || certificates.length <= 0) return null;
        try {
            CertificateFactory factory = CertificateFactory.getInstance("X.509");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            int index = 0;
            for (InputStream certificate : certificates) {
                String certificatesAlias = Integer.toString(index++);
                keyStore.setCertificateEntry(certificatesAlias, factory.generateCertificate(certificate));
                if (certificate != null) {
                    certificate.close();
                }
            }
            TrustManagerFactory managerFactory;
            managerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            managerFactory.init(keyStore);
            return managerFactory.getTrustManagers();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static KeyManager[] prepareKeyManager(InputStream bkfFile, String password) {
        if (bkfFile == null || password == null) return null;
        try {
            KeyStore clientKeyStore = KeyStore.getInstance("BKS");
            clientKeyStore.load(bkfFile, password.toCharArray());
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(clientKeyStore, password.toCharArray());
            return keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static class UnsafeTrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }



    private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) {
        for (TrustManager manager : trustManagers) {
            if (manager instanceof X509TrustManager) {
                return (X509TrustManager) manager;
            }
        }
        return null;
    }
    private static class MyTrustManager implements X509TrustManager {

        X509TrustManager defaultTrustManager;
        X509TrustManager localTrustManager;

        public MyTrustManager(X509TrustManager localTrustManager) throws Exception {
            TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            factory.init((KeyStore) null);
            defaultTrustManager = chooseTrustManager(factory.getTrustManagers());
            this.localTrustManager = localTrustManager;
        }




        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {


        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            try {
                defaultTrustManager.checkServerTrusted(chain, authType);
            } catch (Exception e) {
                localTrustManager.checkServerTrusted(chain, authType);
            }

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }
}
